package com.zjf.carpark.utils;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: 张建飞
 * Date: 2019/11/29
 * Time: 8:53
 * To change this template use File | Settings | File Templates.
 * Description:文件上传工具类
 */
public class FileUploadUtil {
    private static ResponseData responseData = new ResponseData();

    private FileUploadUtil() {
    }

    /**
     * 文件上传
     *
     * @param file     需要上传的文件
     * @param filePath 上传到的路径，根路径下的路径:"/"+filepath
     * @param request
     * @return 返回响应数据对象
     */
    public static ResponseData fileUpload(MultipartFile file, String filePath, HttpServletRequest request) {
        String fileName = file.getOriginalFilename();
        //获取tomcat的根路径
        String path = request.getServletContext().getRealPath("/" + filePath);
        File uploadFile = new File(path);
        if (!uploadFile.exists()) {
            uploadFile.mkdirs();
        }
        //文件重命名
        //时间格式化格式
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        //获取当前时间并作为时间戳
        String timeStamp = simpleDateFormat.format(new Date());
        fileName = timeStamp + fileName;
        System.out.println(fileName);
        File newFile = new File(path + "/" + fileName);
        try {
            FileCopyUtils.copy(file.getBytes(), newFile);
        } catch (IOException e) {
            e.printStackTrace();
            responseData.setCode(500);
            responseData.setMessage("文件上传IO流异常");
            return responseData;
        }
        responseData.setCode(0);
        responseData.setMessage("文件上传成功");
        responseData.putDataValue("filePath", filePath + "/" + fileName);
        System.out.println("文件上传成功");
        System.out.println(file.getOriginalFilename());
        return responseData;
    }
}
